'use strict';
const db = uniCloud.database()
const {
	getWxAppid,
	getSecret
} = require('security')
let wxappid = getWxAppid('wx')
let wxSecret = getSecret('wx')
let qqappid = getWxAppid('qq')
let qqSecret = getSecret('qq')
exports.main = async (event, context) => {
	let wxaccess_token = await wxGetAccessToken()
	let qqaccess_token = await qqGetAccessToken()
	uniCloud.logger.info(wxaccess_token,qqaccess_token)
	let result =await db.collection('wxinfo').doc('5e9b1dc2d83f84004d43a61e').update({
		accesstoken: wxaccess_token
	})
	let qresult =await db.collection('wxinfo').doc('5e9ee85bd2993e004d771c2d').update({
		accesstoken: qqaccess_token
	})
	//返回数据给客户端
	return {result,qresult};
}
async function wxGetAccessToken() {
	const res = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxappid}&secret=${wxSecret}`, {
			dataType: 'json'
		})
	if (res.data.access_token) {
		return res.data.access_token
	} else {
		wxGetAccessToken()
	}
}
async function qqGetAccessToken() {
	const res = await uniCloud.httpclient.request(
		`https://api.q.qq.com/api/getToken?grant_type=client_credential&appid=${qqappid}&secret=${qqSecret}`, {
			dataType: 'json'
		})
	if (res.data.access_token) {
		return res.data.access_token
	} else {
		qqGetAccessToken()
	}
}
